package com.team.easybuy.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.team.easybuy.entity.Car;
import com.team.easybuy.entity.Order;
import com.team.easybuy.entity.OrderDetail;
import com.team.easybuy.service.OrderService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @RequestMapping("/getOrderPage")
    public PageInfo<Order> getOrderPage(Integer userId, Integer isPay, Integer refund,Integer pageNum, Integer pageSize) {
        return orderService.getOrderPage(userId, isPay,refund, pageNum, pageSize);
    }

    @RequestMapping("/showOrderDetil")
    public List<OrderDetail> showOrderDetil(Integer orderId) {
        return orderService.getOrderDetailList(orderId);
    }

    @RequestMapping("/delOrder")
    public String delOrder(Integer id) {
        String rs = null;
        if (orderService.delOrder(id)) {
            rs = "yes";
        } else {
            rs = "no";
        }
        return rs;
    }

    @RequestMapping("/cancelOrder")
    public String cancelOrder(Integer id) {
        String rs = null;
        if (orderService.calorder(id)) {
            rs = "yes";
        } else {
            rs = "no";
        }
        return rs;
    }

    @RequestMapping("/addOrder")
    public Order addOrder(@RequestBody Map<String, Object> params) {
        Order order = JSON.parseObject(JSON.toJSONString(params.get("order")), Order.class);
        order.setCreateTime(new Date());
        order.setIsDelete(0);
        order.setIsPay(0);
        order.setSerialNumber(UUID.randomUUID().toString());
        List<OrderDetail> list = new ArrayList<>();
        List<Car> carList = JSON.parseArray(JSON.toJSONString(params.get("carList")), Car.class);
        for (Car car : carList) {
            OrderDetail orderDetail = new OrderDetail(car.getpId(), car.getpCount(), (car.getpPrice() * car.getpCount()));
            list.add(orderDetail);
        }
        return orderService.addOrder(order, list, carList);
    }

    @RequestMapping("/loadOrder/{id}")
    public Order loadOrder(@PathVariable Integer id) {
        return orderService.loadOrder(id);
    }

    @RequestMapping("/updateRefund")
    public boolean updateRefund(Integer id) {
        return orderService.updateRefund(id);
    }
}
